//
//  PlayerViewController.m
//  BeanSproutEDU
//
//  Created by douya on 15/1/23.
//  Copyright (c) 2015年 douya. All rights reserved.
//

#import "PlayerViewController.h"
#import <MediaPlayer/MediaPlayer.h>
#import "VideoURLPath.h"
#define SCREENWIDTH mainScreen.bounds.size.width
#define SCREENHEIGHT mainScreen.bounds.size.height
@interface PlayerViewController ()

@end

@implementation PlayerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _frameChange=NO;//判断屏幕尺寸是否改变
    _isEnterBackground=NO;//判断是否进入后台
    _sliderValue=0;//这个变量用来暂时性的存储slider的value
    self.player.volume=0.5;//开始播放时将音量设置为中间，以便调音
    self.view.backgroundColor=[UIColor blackColor];//将控制器的背景设置为黑色
    
    
    //－－－－－－－－－－－－－创建暂停、快进、后退的view－－－－－－－－－－－－－//
    [self createIndicatorView];
    
    //－－－－－－－－－－－－－－－初始化AVPlayer－－－－－－－－－－－－－－－－//
    //1、获取沙盒文件
    //    NSString *string=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0] stringByAppendingString:@"/Movie1.m4v"];
    //2、获取工程的文件
    //    NSString *videoString=[[NSBundle mainBundle] pathForResource:@"girl" ofType:@"mp4"];
    //3、获取网络文件
    self.videoURL=@"http://xxr.chocolor.com/Public/video/03002001005375A6BB397401181290DFA52690-06DF-1FBC-51A9-F14A8CC95CAE.mp4";
    [self createAVPlayerWithVideoURL:self.videoURL];
    
    //－－－－－－－－加入点击手势，单击暂停或播放，双击放大或缩小屏幕－－－－－－－//
    [self addGesturRecognizer];
    
    //－－－－－－－－videoSlider的Target事件-－－－－－－－－－－－//
    [self sliderTouchEvent];
    
    //    [self performSelector:@selector(hiddenUpAndDownView) withObject:nil afterDelay:5];
    count=0;
    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(loopToHiddenView) userInfo:nil repeats:YES];
    
}

-(void)loopToHiddenView
{
    count=count+1;
    if (count==5&&isPlaying)
    {
        self.upBackView.hidden=YES;
        self.downBackView.hidden=YES;
    }
}

-(void)hiddenUpAndDownView
{
    self.upBackView.hidden=YES;
    self.downBackView.hidden=YES;
}


#pragma mark- 1、创建AVPlayer
-(void)createAVPlayerWithVideoURL:(NSString *)URL
{
    // 无法播放本地视频  此问题待解决！！！！！问题已解决 是因为网络请求和本地请求url不一样 前者是URLWithString:string  后者是fileURLWithPath:string
    //    NSString *videoString=[[NSBundle mainBundle]pathForResource:@"Movie1" ofType:@"m4v"];
    //    NSURL *url=[NSURL URLWithString:URL];
    NSURL *url=[VideoURLPath getVideoURL:URL];
    
    
    //playerItem 是管理资源的对象
    self.playerItem=[AVPlayerItem playerItemWithURL:url];
    
    [self.playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];//监听status属性(播放器的现状，是处于未知unknown还是已经可以播放readyToPlay 还是失败failed)
    [self.playerItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];//监听loaedTimeRanges属性(此属性代表已经缓冲的进度，监听此属性可以在UI中更新缓冲进度，也是很有用的属性)
    
    self.player=[AVPlayer playerWithPlayerItem:self.playerItem];
    
    
    self.playerView.frame=CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    NSLog(@"%@",NSStringFromCGRect(self.playerView.frame));
    
    self.playerView.player=self.player;
    
    self.playerView.delegate=self;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayDidEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:self.playerItem];//监听是否已经播放完毕
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidEnterBackground:) name:UIApplicationDidEnterBackgroundNotification object:nil];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillResignActive:) name:UIApplicationDidBecomeActiveNotification object:nil];
    
    self.stateButton.enabled=NO;//将播放按钮设置为不可触摸
    [self isPlaying:NO];//一开始不能播放
    isPlaying=NO;
    
    
}

#pragma mark 键值观察 判断视频是否可以播放 或者 判断其缓冲了多少
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    AVPlayerItem *playerItem=(AVPlayerItem *)object;
    
    if ([keyPath isEqualToString:@"status"])
    {
        if ([playerItem status]==AVPlayerStatusReadyToPlay)//判断视频是否可以播放
        {
            //            NSLog(@"视频可以播放了");
            self.stateButton.enabled=YES;
            //获取视频总长度
            CMTime duration=self.playerItem.duration;
            //总秒数
            _totalSecond=playerItem.duration.value/playerItem.duration.timescale;//转换成秒
            
            _totalTime=[self convertTime:_totalSecond];//转换成播放时间
            
            [self customVideoSlider:duration];//自定义UISlider外观
            
            //            NSLog(@"视频总长度:%f",CMTimeGetSeconds(duration));
            
            //监听播放状态
            [self monitoringPlayback:self.playerItem];
            
            if (!_isEnterBackground)
            {
                [self isPlaying:YES];//可以开始播放了
                
                isPlaying=YES;
            }
            
            
        }
        else if ([playerItem status] == AVPlayerStatusFailed)
        {
            NSLog(@"视频播放失败");
            
        }
        
    }else if([keyPath isEqualToString:@"loadedTimeRanges"])//loadedTimeRanges随时有改变 因此会不断的触发此方法
    {
        NSTimeInterval timeInterval=[self availableDuration];//计算缓冲时间
        //        NSLog(@"缓冲了的时间长度:%f",timeInterval);
        CMTime duration=self.playerItem.duration;//获取视频总长度
        CGFloat totalDuration=CMTimeGetSeconds(duration);//将视频总长度转换为秒
        
        //更新缓冲进度条
        [self.videoProgress setProgress:timeInterval/totalDuration animated:YES];
    }
}

#pragma mark 计算已经缓冲了的时间长度
-(NSTimeInterval)availableDuration
{
    NSArray *loadedTimeRanges=self.player.currentItem.loadedTimeRanges;
    if ([loadedTimeRanges count]>0)
    {
        CMTimeRange timeRange=[[loadedTimeRanges objectAtIndex:0] CMTimeRangeValue];//获取缓冲区域
        float startSeconds=CMTimeGetSeconds(timeRange.start);
        float durationSeconds=CMTimeGetSeconds(timeRange.duration);
        
        return (startSeconds+durationSeconds);//计算缓冲总进度
    }else
    {
        return 0.0f;
    }
    
}
#pragma mark 将时间格式化 以02:23的样式显示出来
-(NSString *)convertTime:(CGFloat)second
{
    NSDate *d=[NSDate dateWithTimeIntervalSince1970:second];//返回以1970/01/01 GMT为基准，然后过了secs秒的时间
    
    NSDateFormatter *formatter=[[NSDateFormatter alloc] init];//创建时间显示形式
    
    if (second/3600>=1)//如果总秒数大于1个小时 那么它的显示形式就是小时：分：秒
    {
        [formatter setDateFormat:@"HH:mm:ss"];
    }
    else//否则以分：秒
    {
        [formatter setDateFormat:@"mm:ss"];
    }
    NSString *showtimeNew=[formatter stringFromDate:d];
    
    return showtimeNew;
}
#pragma mark 监视播放状态 以此来更新slider (monitoring监视、监听)
-(void)monitoringPlayback:(AVPlayerItem *)playerItem
{
    //CMTimeMake(time,timeScale)顾名思义就是用来建立CMTime用的 CMTime是专门用来表示影片时间用的 time指的是时间不是秒，而要将时间转换成秒那么就要看第二个参数timeScale了，因此真正要表达的时间就是time/timeScale才会是秒
    //参数1:interval时间间隔  这里设置的一秒 也就是一秒钟圆点向前走一步  参数2:队列，传null是代表在主线程中执行 参数3:是一个block代码块 用来计算已经播放了多少秒并更新UI
    [self.playerView.player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:NULL usingBlock:^(CMTime time){
        
        CGFloat currentSecond=playerItem.currentTime.value/playerItem.currentTime.timescale;//计算当前在第几秒
        
        [self updateVideoSlider:currentSecond];//更新进度条Slider
        
        NSString *timeString=[self convertTime:currentSecond];//将当前播放的时间格式化
        
        self.timeLabel.text=[NSString stringWithFormat:@"%@/%@",timeString,_totalTime];//将播放时间和总时间进行格式化 -－> 00:03/01:27
        
    }];
    
}

#pragma mark 自定义UISlider的轨道样式
-(void)customVideoSlider:(CMTime)duration
{
    self.videoSlider.maximumValue=CMTimeGetSeconds(duration);//设置slider的最大值 也就是slider的长度
    self.videoSlider.minimumTrackTintColor=[UIColor redColor];
    //按我的理解 以下三步是为了画出一个透明的图 然后加载到slider进度条的前后 以达到隐藏它本身的蓝色线条
    UIGraphicsBeginImageContextWithOptions((CGSize){2,2}, NO, 0.0f);//参数1:设置线条的尺寸 也就是是粗细 两个数字要相等 数字越大则越粗  参数2:是否透明 NO代表透明 YES代表不透明 参数3:代表尺寸
    
    UIImage *transparentImage=UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    
    //    [self.videoSlider setMinimumTrackImage:transparentImage forState:UIControlStateNormal];//将创建的透明图片加载到上文的轨道
    [self.videoSlider setMaximumTrackImage:transparentImage forState:UIControlStateNormal];//将创建的透明图片加载到下文的轨道
}

#pragma mark 更新slider
-(void)updateVideoSlider:(NSTimeInterval)time
{
    self.videoSlider.value=time;
}

#pragma mark 播放完毕的方法
-(void)moviePlayDidEnd:(NSNotification *)notification
{
    NSLog(@"播放完毕");
}



#pragma mark- 2、加入手势
-(void)addGesturRecognizer
{
    //-----------加入点击手势，单击暂停或播放，双击放大或缩小屏幕-----------------//
    UITapGestureRecognizer *oneTap=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(oneTap:)];
    oneTap.numberOfTapsRequired=1;
    [self.playerView addGestureRecognizer:oneTap];
    
    UITapGestureRecognizer *twoTap=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(twoTap:)];
    twoTap.numberOfTapsRequired=2;
    [self.playerView addGestureRecognizer:twoTap];
    
    [oneTap requireGestureRecognizerToFail:twoTap];//防止双击被单击拦截
    
    
    //-----------加入捏合手势，捏合以适应屏幕尺寸-----------------//
    UIPinchGestureRecognizer *pinch=[[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(pinchChangeFrame:)];
    [self.playerView addGestureRecognizer:pinch];
    
}
#pragma mark 单击暂停或者播放
-(void)oneTap:(UITapGestureRecognizer *)gesture
{
    isPlaying=!isPlaying;
    [self isPlaying:isPlaying];
    if (isPlaying)
    {
        [self indicatorViewWithImageView:@"moviePlay" withLabelText:@"开始" isSlider:YES];
        self.indicatorView.hidden=YES;
        [self performSelector:@selector(hiddenUpAndDownView) withObject:nil afterDelay:5];
        count=0;
    }
    else
    {
        self.upBackView.hidden=NO;
        self.downBackView.hidden=NO;
        [self indicatorViewWithImageView:@"moviePause" withLabelText:@"暂停" isSlider:YES];
        count=6;
    }
    
}
#pragma mark 双击放大或者缩小
-(void)twoTap:(UITapGestureRecognizer *)gesture
{
    if (self.playerView.transform.a<1)
    {
        self.playerView.transform=CGAffineTransformMake(1, 0, 0, 1, 0, 0);
        _frameChange=NO;
    }
    else
    {
        self.playerView.transform=CGAffineTransformMake(0.8, 0, 0, 0.8, 0, 0);
        _frameChange=YES;
    }
    
    [self setBtnOfFullScreen];
}
#pragma mark 手势  捏合  改变屏幕尺寸
-(void)pinchChangeFrame:(UIPinchGestureRecognizer *)pinch
{
    NSLog(@"捏合手势响应");
    if (self.playerView.transform.a<0.5)
    {
        _frameChange=YES;
        [self setBtnOfFullScreen];
        if (pinch.scale<1)
        {
            return;
        }
        else
        {
            self.playerView.transform=CGAffineTransformScale(self.playerView.transform, pinch.scale, pinch.scale);
            pinch.scale=1;
        }
    }
    else if (self.playerView.transform.a>1)
    {
        _frameChange=NO;
        [self setBtnOfFullScreen];
        if (pinch.scale>1)
        {
            return;
        }
        else
        {
            self.playerView.transform=CGAffineTransformScale(self.playerView.transform, pinch.scale, pinch.scale);
            pinch.scale=1;
        }
    }
    else
    {
        _frameChange=YES;
        [self setBtnOfFullScreen];
        self.playerView.transform=CGAffineTransformScale(self.playerView.transform, pinch.scale, pinch.scale);
        pinch.scale=1;
        if (self.playerView.transform.a<0.5||self.playerView.transform.a>1)
        {
            return;
        }
        
        
    }
    
    
}





#pragma mark- 3、slider按钮事件
-(void)sliderTouchEvent
{
    [self.videoSlider addTarget:self action:@selector(sliderIsScrolling:) forControlEvents:UIControlEventValueChanged];//控制slider按钮滑动事件
    
    [self.videoSlider addTarget:self action:@selector(sliderNotScrolling:) forControlEvents:UIControlEventTouchUpInside];//监听slider按钮松开事件
}

#pragma mark 按动滑块快进或者后退
-(void)sliderIsScrolling:(UISlider *)slider
{
    if (_sliderValue<slider.value)//用一个变量来记录上一次slider的值用来判断slider是在快进还是后退
    {
        [self indicatorViewWithImageView:@"movieForward" withLabelText:@"快进" isSlider:YES];
    }
    else
    {
        [self indicatorViewWithImageView:@"movieBackward" withLabelText:@"快退" isSlider:YES];
    }
    
    CMTime cTime=self.playerItem.duration;
    
    CGFloat totalDuration=CMTimeGetSeconds(cTime);
    
    double currentTime=floor(totalDuration *self.videoSlider.value/100);
    //
    //    NSLog(@"currentTime----%f---%f",currentTime,self.videoSlider.value/100);
    
    
    CMTime dragedCMTime=CMTimeMake(currentTime, 1);
    [self.player seekToTime:dragedCMTime completionHandler:^(BOOL finished){
        //        NSLog(@"是按动滑块实现的");
    }];
    
}
#pragma mark 结束滑动
-(void)sliderNotScrolling:(UISlider *)slider
{
    self.indicatorView.hidden=YES;
    _sliderValue=slider.value;
}



#pragma mark-  4、创建暂停、快进、后退的view
-(void)createIndicatorView
{
    UIScreen *mainScreen=[UIScreen mainScreen];//获取手机屏幕的物理尺寸
    self.indicatorView=[[IndicatorView alloc] initWithFrame:CGRectMake(SCREENHEIGHT/2-50, SCREENWIDTH/2-50, 100, 100)];
    self.indicatorView.hidden=YES;
    self.indicatorView.delegate=self;
    self.indicatorView.clipsToBounds=YES;
    self.indicatorView.layer.cornerRadius=5;
    self.indicatorView.backgroundColor=[UIColor colorWithWhite:0.5 alpha:0.5];
    [self.view addSubview:self.indicatorView];
}
-(void)IndicatorView:(IndicatorView *)indicatorView playOrpause:(BOOL)play
{
    [self indicatorViewWithImageView:@"moviePlay" withLabelText:@"播放" isSlider:YES];
    [self.stateButton setImage:[UIImage imageNamed:@"moviePause"] forState:UIControlStateNormal];
    isPlaying=YES;
    [self.player play];
    self.indicatorView.hidden=YES;
    count=0;
}



#pragma mark 控制indicatorView的显示
-(void)indicatorViewWithImageView:(NSString *)imageName withLabelText:(NSString *)text isSlider:(BOOL)isSlider
{
    self.indicatorView.hidden=NO;
    if([imageName isEqualToString:@"moviePause"]||[imageName isEqualToString:@"moviePlay"])
    {
        self.indicatorView.button.hidden=NO;
        self.indicatorView.imageView.hidden=YES;
        [self.indicatorView.button setBackgroundImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    }
    else
    {
        self.indicatorView.button.hidden=YES;
        self.indicatorView.imageView.hidden=NO;
        self.indicatorView.imageView.image=[UIImage imageNamed:imageName];
    }
    self.indicatorView.label.text=text;
    if (!isSlider)
    {
        [self performSelector:@selector(indicatorViewHidden) withObject:nil afterDelay:2];
    }
}
-(void)indicatorViewHidden
{
    self.indicatorView.hidden=YES;
}





#pragma mark 点击满屏按钮
- (IBAction)fullScreenBtn:(UIButton *)sender
{
    if (_frameChange)
    {
        self.playerView.transform=CGAffineTransformMake(1, 0, 0, 1, 0, 0);
        _frameChange=NO;
    }
    else
    {
        self.playerView.transform=CGAffineTransformMake(0.8, 0, 0, 0.8, 0, 0);
        _frameChange=YES;
    }
    [self setBtnOfFullScreen];
}
-(void)setBtnOfFullScreen
{
    if (_frameChange)
    {
        [self.fullScreenBtn setImage:[UIImage imageNamed:@"movieFullscreen"] forState:UIControlStateNormal];
    }
    else
    {
        [self.fullScreenBtn setImage:[UIImage imageNamed:@"movieEndFullscreen"] forState:UIControlStateNormal];
    }
}


#pragma mark 点击暂停或则播放按钮
- (IBAction)playBtn:(UIButton *)sender
{
    
    isPlaying=!isPlaying;
    [self isPlaying:isPlaying];
    if (isPlaying)
    {
        [self indicatorViewWithImageView:@"moviePlay" withLabelText:@"开始" isSlider:YES];
        self.indicatorView.hidden=YES;
        count=0;
    }
    else
    {
        [self indicatorViewWithImageView:@"moviePause" withLabelText:@"暂停" isSlider:YES];
        count=6;
    }
    
}

-(void)isPlaying:(BOOL)playing
{
    if (playing)
    {
        [self.stateButton setImage:[UIImage imageNamed:@"moviePause"] forState:UIControlStateNormal];
        [self.player play];
    }
    else
    {
        [self.stateButton setImage:[UIImage imageNamed:@"moviePlay"] forState:UIControlStateNormal];
        [self.player pause];
    }
}

#pragma mark- 快进
- (IBAction)speedDownBtn:(UIButton *)sender
{
    [self indicatorViewWithImageView:@"movieForward" withLabelText:@"快进" isSlider:NO];
    _sliderValue=self.videoSlider.value;
    CMTime currentTime=self.player.currentItem.currentTime;//获取当前已经播放的时间
    float currentDuration=currentTime.value/currentTime.timescale;
    
    //    [self availableDuration];//计算缓冲的时间长度
    
    [self speedWithCurrentDuration:currentDuration];//快进
}

-(void)speedWithCurrentDuration:(CGFloat)currentDuration
{
    CGFloat newTime=currentDuration+5;//在当前的时间的基础上加5秒
    CGFloat totaleTime=CMTimeGetSeconds(self.playerItem.duration);
    if (newTime>=totaleTime)
    {
        return;
    }
    
    //转换成CMTime才能给player来控制播放进度
    //以下是实现快进的关键性代码
    CMTime dragedCMTime=CMTimeMake(newTime, 1);
    [self.player seekToTime:dragedCMTime completionHandler:^(BOOL finished){
        //        NSLog(@"按钮快进");
    }];
    
}
#pragma mark- 后退
- (IBAction)retreatDownBtn:(UIButton *)sender
{
    [self indicatorViewWithImageView:@"movieBackward" withLabelText:@"后退" isSlider:NO];
    _sliderValue=self.videoSlider.value;
    CMTime currentTime=self.player.currentItem.currentTime;//获取当前已经播放的时间
    float currentDuration=currentTime.value/currentTime.timescale;
    
    //    [self availableDuration];//计算缓冲的时间长度
    
    [self retreatWithCurrentTime:currentDuration];
}



-(void)retreatWithCurrentTime:(CGFloat)currentTime
{
    CGFloat newTime=currentTime-5;
    if (newTime<=0.0)
    {
        return;
    }
    
    //转换成CMTime才能给player
    CMTime dragedCMTime=CMTimeMake(newTime, 1);
    [self.player seekToTime:dragedCMTime completionHandler:^(BOOL finished){
        //        NSLog(@"按钮快退");
    }];
    
    
}


#pragma mark- 滑动屏幕加速
-(void)TouchSpeed
{
    [self speedDownBtn:nil];
}

#pragma mark- 滑动屏幕后退
-(void)TouchRetreat
{
    [self retreatDownBtn:nil];
}

#pragma mark- 进入后台的通知
-(void)applicationDidEnterBackground:(NSNotification *)notification
{
    [self.player pause];
    _isEnterBackground=YES;
}

#pragma mark- 应用被激活的通知
-(void)applicationWillResignActive:(NSNotification *)notification
{
    [self.player play];
}


//支持旋转
-(BOOL)shouldAutorotate
{
    return YES;
}
//支持向右旋转
- (NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskLandscapeRight;
}


//获取缓存的总大小
-(float)getSize
{
    NSString *directoryPath=[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    
    NSDirectoryEnumerator *enumerator=[[NSFileManager defaultManager] enumeratorAtPath:directoryPath];
    
    long long size=0;
    
    while ([enumerator nextObject])
    {
        size += enumerator.fileAttributes.fileSize;
    }
    
    NSLog(@"%lld",size);
    
    float floatSize=size/1000.0/1000.0;
    return floatSize;
    
}

- (IBAction)backMainViewController:(UIButton *)sender
{
    [self dismissViewControllerAnimated:YES completion:nil];
    [self.player pause];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
